import React, { PureComponent } from 'react'
import {
  Button, Form, Input, message, Modal, Popconfirm, Switch,
} from 'antd'
import { connect } from '@umijs/max'
import {
  BreadcrumbBar, InputSearch, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import styles from './index.less'
import JSEncrypt from '@/utils/JSEncrypt.js'
import AccountModal from './accountModal'
// import { delUser, editUser, getAllAccount } from './api'
import { getAllAccount } from './api'
import { regExp } from '@/utils/regExp'

const { Item } = Form
const { OperateItem } = ProTableOperate
const menus = [{ name: '系统管理' }, { name: '用户管理' }]

@connect(({ global }) => ({ ...global }))
export default class Account extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: '账号',
          dataIndex: 'id',
          width: '10%',
          key: 'username',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          width: '15%',
          key: 'email',
        },
        {
          title: '手机号',
          dataIndex: 'phoneNumber',
          width: '15%',
          key: 'phone',
        },
        {
          title: '姓名',
          dataIndex: 'displayName',
          width: '10%',
          key: 'name',
        },
        // {
        //   title: '角色',
        //   dataIndex: 'roleName',
        //   width: '10%',
        //   key: 'roleName',
        // },
        {
          title: '创建时间',
          dataIndex: 'created',
          width: '15%',
          key: 'createTime',
        },
        // {
        //   title: '是否启用',
        //   dataIndex: 'abled',
        //   width: '10%',
        //   key: 'abled',
        //   render: (text, record, index) => (
        //     <Switch
        //       checked={!!record.rowState}
        //       disabled={(!(this.state.isAdmin || record.id === this.props.user.id)) || record.isAuth}
        //       onChange={(e) => {
        //         this.onRowStateChange(e, record.id)
        //       }}
        //     />
        //   ),
        // },
        // {
          // title: '操作',
          // dataIndex: 'operation',
          // width: '15%',
          // key: 'operation',
          // render: (text, record, index) => {
          //   const { user } = this.props
          //   const { isAuth } = user
          //   return <ProTableOptions size={4}>
              // {/* <span
              //   onClick={() => { this.onCheck(record) }}
              //   key="check"
              // >
              //   查看
              // </span> */}
              // {/* {
          //       (this.state.isAdmin || record.id === this.props.user.id) && (
          //         <span
          //           onClick={() => { this.onEdit(record) }}
          //           key="edit"
          //         >
          //           编辑
          //         </span>
          //       )
          //     }
          //     {
          //       (this.state.isAdmin || record.id === this.props.user.id) && (
          //         <span
          //           onClick={() => { this.onReset(record) }}
          //           key="reset"
          //         >
          //           重置密码
          //         </span>
          //       )
          //     }
          //     {
          //       ((this.state.isAdmin || record.id === this.props.user.id) && !record.isAuth || isAuth == 2) && isAuth != 3 && (
          //         <Popconfirm
          //           title="你确定要删除这个用户吗？"
          //           okText="确定"
          //           cancelText="取消"
          //           onConfirm={() => { this.onDelete(record) }}
          //           key="delPop"
          //         >
          //           <span>
          //             删除
          //           </span>
          //         </Popconfirm>
          //       )
          //     } */}
          //   </ProTableOptions>
          // },
        // },
      ],
      visible: false,
      accountModalIsEdit: false,
      accountModalIsCheck: false,
      name: '',
      query: {},
      id: '',
      loading: false,
      isAdmin: false,
    }

    this.formRef = React.createRef()
    this.accountModalRef = React.createRef()
  }

  componentDidMount() {
    // this.checkSelfAccount()
  }

  onCheck = (record) => {
    this.setState({
      accountModalIsEdit: false,
      accountModalIsCheck: true,
    }, () => {
      this.accountModalRef.current.openEditModal(record)
    })
  }

  // onRowStateChange(checked, id) {
  //   this.setState({ loading: true })
  //   editUser({
  //     id,
  //     rowState: checked ? 1 : 0,
  //   }).then(
  //     (res) => {
  //       this.setState({
  //         visible: false,
  //         loading: false,
  //       }, () => {
  //         this.fetchData()
  //       })
  //     },
  //     (error) => {
  //       console.log(error)
  //       this.setState({ loading: false })
  //     },
  //   )
  // }

  checkSelfAccount = () => {
    this.setState({ loading: true })
    getAllAccount({
      pageSize: 999,
      pageNum: 1,
    }).then(
      (res) => {
        const arr = res.result
        const obj = arr.find((item) => item.id === this.props.user.id)
        const { isAuth } = this.props?.user || {}
        if (obj && obj.roleName === '系统管理员' || isAuth == 3) {
          this.setState({ isAdmin: true }, () => {
            this.fetchData()
          })
        }
        this.setState({ loading: false })
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  onEdit = (record) => {
    this.setState({
      accountModalIsEdit: true,
      accountModalIsCheck: false,
    }, () => {
      this.accountModalRef.current.openEditModal(record)
    })
  }

  onReset = (data) => {
    this.setState({
      visible: true,
      id: data.id,
    }, () => {
      this.formRef.current && this.formRef.current.resetFields()
    })
  }

  onDelete = (data) => {
    this.setState({ loading: true })
    delUser({ id: data.id }).then(
      (res) => {
        message.success('删除用户成功')
        this.fetchData()
        this.setState({ loading: false })
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  showAccountModal = () => {
    this.setState({
      accountModalIsEdit: false,
      accountModalIsCheck: false,
    }, () => {
      this.accountModalRef.current.openModal()
    })
  }

  fetchData = async () => {
    const { name } = this.state
    const tempQuery = {}
    if (name && name !== '') tempQuery.id = name
    this.setState({
      query: tempQuery,
    })
  }

  onCloseCallBack = () => {
    this.fetchData()
  }

  // onConfirm = () => {
  //   this.formRef.current.validateFields().then(values => {
  //     this.setState({ loading: true })
  //     editUser({
  //       id: this.state.id,
  //       password: JSEncrypt(values.password),
  //     }).then(
  //       (res) => {
  //         message.success('重置密码成功')
  //         this.setState({
  //           visible: false,
  //           loading: false,
  //         }, () => {
  //           this.fetchData()
  //         })
  //       },
  //       (error) => {
  //         console.log(error)
  //         this.setState({ loading: false })
  //       },
  //     )
  //   })
  // }

  render() {
    const {
      visible, accountModalIsEdit, accountModalIsCheck, query, loading,
    } = this.state
    const { user } = this.props
    const { isAuth } = user
    const passwordReg = regExp.password(8, 32)
    return (
      <div className={styles.page_content_with_breadcrumb}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.page_content}>
          <div className={styles.page_content_right}>
            <ProTableOperate
              toggleOperate={false} // 是否隐藏 收起/展开 按钮 (如果隐藏按钮，handleToggleSta设置属性值不生效)
              unfolded // 默认展开状态
            >
              <OperateItem align="left">
                <InputSearch
                  placeholder="请输入账号进行搜索"
                  value={this.state.name}
                  onChange={(e) => {
                    this.setState({
                      name: e.target.value,
                    }, () => {
                      this.fetchData()
                    })
                  }}
                  onSearch={this.fetchData}
                />
              </OperateItem>
              {/* {isAuth == 3 ? null : <OperateItem itemType="btn">
                {
                  [
                    <Button
                      onClick={this.showAccountModal}
                      type="primary"
                      loading={loading}
                      key="new"
                    >
                      新增用户
                    </Button>,
                  ]
                } */}
              {/* </OperateItem>} */}
            </ProTableOperate>
            <ProTable
              columns={this.state.columns}
              url="/api/v1/management/user/project/getUserPageList"
              query={query}
              loading={loading}
            />
          </div>
          <AccountModal
            ref={this.accountModalRef}
            isEdit={accountModalIsEdit}
            isCheck={accountModalIsCheck}
            closeCallBack={this.onCloseCallBack}
            user={user}
          />
          <Modal
            title="重置密码"
            visible={visible}
            width={520}
            onCancel={() => { this.setState({ visible: false }) }}
            maskClosable={false}
            onOk={this.onConfirm}
            okButtonProps={{
              loading,
            }}
          >
            <Form
              ref={this.formRef}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
            >
              <Item
                label="新密码"
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  {
                    pattern: new RegExp(passwordReg.reg, 'g'),
                    message: passwordReg.text,
                  },
                ]}
              >
                <Input.Password placeholder="请输入密码" />
              </Item>
              <Item
                label="确认密码"
                name="confirm"
                dependencies={['password']}
                rules={
                  [
                    {
                      required: true, message: '请再次输入密码',
                    },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve()
                        }
                        return Promise.reject(new Error('两次输入的密码不相同'))
                      },
                    }),
                  ]
                }
              >
                <Input.Password placeholder="请再次输入密码" />
              </Item>
            </Form>
          </Modal>
        </div>
      </div>
    )
  }
}
